package solutions.leetcode.normal

/**
 * @author lizhidong
 * <a href="https://leetcode.cn/problems/minimum-operations-to-make-array-equal-ii/">2541. 使数组中所有元素相等的最小操作数 II</a>
 */
private class Solution2541 {
    /*
    1   3   4   4
    1   1   3   7
     */
    fun minOperations(nums1: IntArray, nums2: IntArray, k: Int): Long {
        var c: Long = 0
        var r: Long = 0
        for (i in nums1.indices) {
            val offset = nums2[i] - nums1[i]
            if (offset == 0) {
                continue
            }
            if (k == 0 || offset % k != 0) {
                return -1
            }
            val s = offset / k
            if ((c > 0 && s > 0) || (c < 0 && s < 0)) {
                c += s
                r += Math.abs(s)
            } else {
                if (Math.abs(c) > Math.abs(s)) {
                    c += s
                } else {
                    c += s
                    r += Math.abs(c)
                }
            }
        }
        return if (c == 0L) r else -1
    }
}

fun main() {
    println(
        Solution2541().minOperations(
            arrayOf(
                4,3,1,4
            ).toIntArray(),
            arrayOf(
                1,3,7,1
            ).toIntArray(),
            3
        )
    )
}